package com.test.utils;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Date;

import com.alibaba.fastjson.JSONObject;
import com.test.Constants;
import com.test.WeiXinHttpHelper;

/**
 * 微信 access_token工具类
 * 
 * @author 殷田
 *
 */
public class AccessTokenUtil {
	private static String access_token;
	private static Date access_token_date;
	private static long accessTokenInvalidTime = 2 * 60 * 60;

	private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";

	public static String getToken() throws Exception {
		if (!isValid()) {
			String rest = WeiXinHttpHelper.getAccessToken(Constants.AppID, Constants.AppSecret);
			JSONObject json = JSONObject.parseObject(rest);
			String token = json.getString("access_token");
			if (token != null) {
				access_token_date = new Date();
				access_token = token;
				accessTokenInvalidTime = json.getLongValue("expires_in");
			}
		}
		return access_token;
	}

	public static boolean isValid() {
		if (access_token == null || access_token.length() == 0) {
			return false;
		}
		long interval = new Date().getTime() - access_token_date.getTime();
		if (interval > (accessTokenInvalidTime - 200000L)) {
			return false;
		}
		return true;
	}
}
